import { DBBase } from "../base/DBBase";
import { Provide,Inject } from '@midwayjs/decorator';
import { RedisService } from "@midwayjs/redis";
import { SystemConfigType } from "../interfaces/ISystem.interface";
import { SystemInfo } from "../entity/system.entity";
import { Repository } from "typeorm";
import { ErrCode } from "../common/ErrCode";
import { RedisKey } from "../interfaces/IBase.interface";
import { Tools } from "../common/Tools";

@Provide()
export class SystemConfigService extends DBBase{
    @Inject()
    redisService:RedisService;

    async setSystemConfig(type:SystemConfigType,datas:string):Promise<ErrCode>{
        let configs:Repository<SystemInfo> = await this.Repository({entities:SystemInfo});
        let config:SystemInfo = await configs.findOne({where:{type:type}});
        if(config == null){
            config = new SystemInfo();
            config.type = type;
        }
        config.data = datas;//JSON.stringify(datas);
        try {
            await configs.save(config);
            return ErrCode.SYSTEM_CONFIG_SUCCESS;
        } catch (error) {
            console.error(error);
            return ErrCode.SYSTEM_CONFIG_FAIL;
        }
    }

    async getSystemConfig(type:SystemConfigType):Promise<any>{
        let configs:Repository<SystemInfo> = await this.Repository({entities:SystemInfo});
        let rkey:string = RedisKey.SystemConfigBaseKey+type;
        let configData:string = await this.redisService.get(rkey);
        if(configData != null && configData != ""){
            return JSON.parse(configData);
        }else{
            let config:SystemInfo = await configs.findOne({where:{type:type}});
            if(config != null){
                await this.redisService.set(rkey,config.data,'EX',(10*60));
                return Tools.formatData(JSON.parse(config.data));
            }else{
                return null;
            }
        }
    }

}